package com.mapapp.flutter_mapapp.activity;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import com.blankj.utilcode.util.Utils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.mapapp.flutter_mapapp.R;
import com.mapapp.flutter_mapapp.adapter.UploadDataAdapter;
import com.mapapp.flutter_mapapp.application.Constants;
import com.mapapp.flutter_mapapp.application.MyApplication;
import com.mapapp.flutter_mapapp.bean.NewDataProcessBean;
import com.mapapp.flutter_mapapp.bean.WaitForUploading;
import com.mapapp.flutter_mapapp.bean.WaitForUploadingDao;
import com.mapapp.flutter_mapapp.http.Url;
import com.mapapp.flutter_mapapp.persenter.NewDataPresenter;
import com.mapapp.flutter_mapapp.service.AudioRecordService;
import com.mapapp.flutter_mapapp.util.FTPClientFunctions;
import com.mapapp.flutter_mapapp.util.SharePreferenceUtil;
import com.mapapp.flutter_mapapp.util.ToastUtils;
import com.mapapp.flutter_mapapp.view.NewDataViewInterface;
import com.mapapp.flutter_mapapp.widget.DeleteDataDialog;
import com.mapapp.flutter_mapapp.widget.TitleBar;
import com.mapapp.flutter_mapapp.widget.UploadDataProgressDialog;

import org.apache.commons.net.ftp.FTPClient;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class UploadDataActivity extends ImmersiveBaseActivity implements NewDataViewInterface {
    @BindView(R.id.title_bar)
    TitleBar titleBar;
    @BindView(R.id.bg_select_all)
    View bgSelectAll;
    @BindView(R.id.iv_check)
    ImageView ivCheck;
    @BindView(R.id.rv_data_for_uploading)
    RecyclerView rvDataForUploading;
    private UploadDataAdapter uploadDataAdapter;

    private NewDataPresenter presenter;

    private UploadDataProgressDialog uploadDataProgressDialog;

    private List<String> regionIds = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload_data);
        ButterKnife.bind(this);
        presenter = new NewDataPresenter(this, this, lifecycleSubject);


        String userId = (String) SharePreferenceUtil.get(mContext, Constants.USERNAME, "");
        //清除缓存
        MyApplication.getInstance().getDaoSession().getWaitForUploadingDao().detachAll();
        List<WaitForUploading> waitForUploadingList =
                MyApplication.getInstance().getDaoSession().getWaitForUploadingDao()
                        .queryBuilder().where(WaitForUploadingDao.Properties.UserId.eq(userId),
                        WaitForUploadingDao.Properties.HostAddress.eq(Url.BASE_URL)).list();

        if (waitForUploadingList == null || waitForUploadingList.isEmpty()) {
            ToastUtils.showMessage(mContext, "暂无数据");
            return;
        }

        uploadDataAdapter = new UploadDataAdapter(R.layout.item_upload_data, waitForUploadingList);
        rvDataForUploading.setLayoutManager(new LinearLayoutManager(mContext));
        rvDataForUploading.setAdapter(uploadDataAdapter);
        uploadDataAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                uploadDataAdapter.getData().get(position).setSelect(!uploadDataAdapter.getData().get(position).isSelect());
                uploadDataAdapter.notifyDataSetChanged();

                boolean allSelected = false;
                for (WaitForUploading datum : uploadDataAdapter.getData()) {
                    if (!datum.isSelect()) {
                        ivCheck.setSelected(false);
                        return;
                    } else {
                        allSelected = true;
                    }
                }
                if (allSelected) {
                    ivCheck.setSelected(true);
                }
            }
        });

        titleBar.getIvBack().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
    }

    private synchronized void upload(final List<String> pathList, final List<String> nameList, final String dirName,
                                     final List<String> audioNames, final String audioDir,
                                     final List<String> childPathList, final List<String> childNameList,
                                     final String childPhotoDir, final WaitForUploading datum) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                FTPClientFunctions ftpClientTool = new FTPClientFunctions();
                ftpClientTool.setListener(new FTPClientFunctions.OnUploadPositionListener() {
                    @Override
                    public void onProgress(final int position, final int total) {
                    }

                    @Override
                    public void onSuccess() {
                        Utils.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                doGet(datum);
                            }
                        });

                    }

                    @Override
                    public void onFailed() {
                        regionIds.remove(datum.getRegionId());
                    }
                });
                boolean connectResult = ftpClientTool.ftpConnect(Url.getInstance().ftpServer, Url.getInstance().ftpUsername, Url.getInstance().ftpPassword, Url.getInstance().ftpPort);
                if (connectResult) {
                    final FTPClient ftpClient = ftpClientTool.getFtpClient();
                    try {
                        if (datum.getAudioName() != null) {
                            ftpClient.changeWorkingDirectory("/radio");
                            ftpClient.makeDirectory(datum.getAudioDirName());
                            boolean radioDir = ftpClient.changeWorkingDirectory("/radio/" + datum.getAudioDirName());
                            if (radioDir) {
                                boolean b = true;
                                for (String audioName : audioNames) {
                                    b = ftpClientTool.ftpUpload(AudioRecordService.FILE_DIR, audioName);
                                    if (!b) {
                                        break;
                                    }
                                }
                                if (b) {
                                    ftpClientTool.ftpUploadList(dirName, pathList, nameList, childPhotoDir, childPathList, childNameList);
                                } else {
                                    showUploadFailed(ftpClientTool, 2, datum.getRegionId());
                                }
                            } else {
                                showUploadFailed(ftpClientTool, 2, datum.getRegionId());
                            }
                        } else {
                            ftpClientTool.ftpUploadList(dirName, pathList, nameList, childPhotoDir, childPathList, childNameList);
                        }
                    } catch (IOException e) {
                        showUploadFailed(ftpClientTool, 2, datum.getRegionId());
                        e.printStackTrace();
                    }
                } else {
                    showUploadFailed(ftpClientTool, 0, datum.getRegionId());
                }

            }
        }).start();
    }

    private void doGet(WaitForUploading datum) {
        switch (datum.getCategory()) {
            case 0:
                presenter.submitProcessNoDialog(datum.getRemark(), datum.getEndTime(), datum.getPhotoDirName(), datum.getProcessId(),
                        datum.getAudioDirName(), datum.getRegionId(), datum.getProcessStartTime(), datum.getState(), datum.getType());
                break;
            case 1:
                presenter.submitSplitRegionNoDialog(datum.getRegionId(), datum.getSeparationHouseholdCount(), datum.getChildRemark(), datum.getAudioDirName(), datum.getChildPhotoDirName());
                break;
            case 2:
                presenter.submitMergeRegionNoDialog(datum.getRegionId(), datum.getMergedIds(), datum.getChildRemark(), datum.getAudioDirName(), datum.getChildPhotoDirName());
                break;
            case 3:
                presenter.submitProcessNoDialog(datum.getRemark(), datum.getEndTime(), datum.getPhotoDirName(), datum.getProcessId(),
                        datum.getAudioDirName(), datum.getRegionId(), datum.getProcessStartTime(), datum.getState(), datum.getType());

                presenter.submitSplitRegionNoDialog(datum.getRegionId(), datum.getSeparationHouseholdCount(), datum.getChildRemark(), datum.getAudioDirName(), datum.getChildPhotoDirName());
                break;
            case 4:
                presenter.submitProcessNoDialog(datum.getRemark(), datum.getEndTime(), datum.getPhotoDirName(), datum.getProcessId(),
                        datum.getAudioDirName(), datum.getRegionId(), datum.getProcessStartTime(), datum.getState(), datum.getType());
                presenter.submitMergeRegionNoDialog(datum.getRegionId(), datum.getMergedIds(), datum.getChildRemark(), datum.getAudioDirName(), datum.getChildPhotoDirName());
                break;
        }
    }


    private void showUploadFailed(final FTPClientFunctions ftpClientTool, final int state, final String regionId) {
        regionIds.remove(regionId);
        ftpClientTool.ftpDisconnect();
        Utils.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (regionIds.isEmpty()) {
                    if (uploadDataProgressDialog != null) {
                        uploadDataProgressDialog.dismiss();
                    }
                }
                switch (state) {
                    case 0:
                        ToastUtils.showMessage(mContext, "连接文件服务器失败");
                        break;
                    case 1:
                        ToastUtils.showMessage(mContext, "本地照片或录音丢失");
                        break;
                    case 2:
                        ToastUtils.showMessage(mContext, "上传文件失败");
                        break;
                }
            }
        });
    }

    @OnClick({R.id.iv_check, R.id.tv_submit, R.id.tv_delete})
    public void onViewClicked(View view) {
        int selectedCount = 0;
        switch (view.getId()) {
            case R.id.tv_delete:
                for (WaitForUploading datum : uploadDataAdapter.getData()) {
                    if (datum.isSelect()) {
                        selectedCount++;
                        break;
                    }
                }
                if (selectedCount == 0) {
                    return;
                }

                DeleteDataDialog deleteDataDialog = new DeleteDataDialog(mContext);
                deleteDataDialog.showPopupWindow();
                deleteDataDialog.setListener(new DeleteDataDialog.OnItemEnsureClickListener() {
                    @Override
                    public void onClick() {
                        List<WaitForUploading> data = uploadDataAdapter.getData();
                        WaitForUploadingDao uploadingDao = MyApplication.getInstance().getDaoSession().getWaitForUploadingDao();
                        for (int i = data.size() - 1; i >= 0; i--) {
                            WaitForUploading bean = data.get(i);
                            if (bean.isSelect()) {
                                uploadDataAdapter.remove(i);
                                uploadingDao.delete(bean);
                            }
                        }
                    }
                });
                break;
            case R.id.tv_submit:

                for (WaitForUploading datum : uploadDataAdapter.getData()) {
                    if (datum.isSelect()) {
                        selectedCount++;
                        break;
                    }
                }
                if (selectedCount == 0) {
                    return;
                }
                regionIds.clear();
                uploadDataProgressDialog = new UploadDataProgressDialog(mContext);
                uploadDataProgressDialog.showPopupWindow();
                for (WaitForUploading datum : uploadDataAdapter.getData()) {
                    if (datum.isSelect()) {
                        regionIds.add(datum.getRegionId());
                        String photosPath = datum.getPhotosPath();
                        String photosName = datum.getPhotosName();
                        String audioName = datum.getAudioName();
                        String childPhotosName = datum.getChildPhotosName();
                        String childPhotosPath = datum.getChildPhotosPath();
                        List<String> pathList = null;
                        List<String> nameList = null;
                        List<String> audioList = null;
                        List<String> childPathList = null;
                        List<String> childNameList = null;
                        if (!TextUtils.isEmpty(photosPath) && !TextUtils.isEmpty(photosName)) {
                            pathList = Arrays.asList(photosPath.split(","));
                            nameList = Arrays.asList(photosName.split(","));
                        }
                        if (audioName != null) {
                            audioList = Arrays.asList(audioName.split(","));
                        }

                        if (!TextUtils.isEmpty(childPhotosName) && !TextUtils.isEmpty(childPhotosPath)) {
                            childPathList = Arrays.asList(childPhotosPath.split(","));
                            childNameList = Arrays.asList(childPhotosName.split(","));
                        }

                        upload(pathList, nameList, datum.getPhotoDirName(), audioList,
                                datum.getAudioDirName(), childPathList, childNameList, datum.getChildPhotoDirName(), datum);
                    }
                }
                break;
            case R.id.iv_check:

                ivCheck.setSelected(!ivCheck.isSelected());

                for (WaitForUploading datum : uploadDataAdapter.getData()) {
                    datum.setSelect(ivCheck.isSelected());
                }
                uploadDataAdapter.notifyDataSetChanged();
                break;
        }

    }

    @Override
    public void showProcess(NewDataProcessBean processBean) {

    }

    @Override
    public void submitProcessStatus(boolean status, String regionId) {
        regionIds.remove(regionId);

        if (regionIds.isEmpty()) {
            if (uploadDataProgressDialog != null) {
                uploadDataProgressDialog.dismiss();
            }
        }
        List<WaitForUploading> data = uploadDataAdapter.getData();
        WaitForUploading bean = null;
        for (WaitForUploading datum : data) {
            if (datum.isSelect() && regionId != null && regionId.equals(datum.getRegionId())) {
                bean = datum;
            }
        }
        if (status) {
            if (bean != null) {
                ToastUtils.showMessage(mContext, bean.getAddress() + "上传成功");
                MyApplication.getInstance().getDaoSession().getWaitForUploadingDao().delete(bean);
                data.remove(bean);
            }
            uploadDataAdapter.notifyDataSetChanged();
        } else {
            if (bean != null) {
                bean.setUploadFailed(true);
                uploadDataAdapter.notifyDataSetChanged();
//                ToastUtils.showMessage(mContext, bean.getAddress() + "上传不成功");
            }
        }
    }
}
